<template>
  <div>
    <!-- aa面包屑 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- aa卡片区 -->
    <el-card>
      <!--bb添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="openAddRole">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- bb表格 -->
      <el-table :data="rolesList" border stripe>
        <!-- cc展开列 -->
        <el-table-column type="expand" label="#">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdBottom', , 'vCenter', i1 === 0 ? 'bdTop' : '']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  :class="['vCenter', i2 === 0 ? '' : 'bdTop']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
          <!-- cc索引列 -->
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="openEditRole(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deletRole(scope.row.id)"
            >
              删除
            </el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
            >
              分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- bb编辑角色对话框 -->
      <el-dialog title="修改信息" width="30%" :visible.sync="editRoleDialog">
        <el-form :model="editRoleForm" label-width="80px">
          <el-form-item label="角色名称">
            <el-input v-model="editRoleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="editRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="editRoleDialog = false">取 消</el-button>
          <el-button type="primary" @click="modifytRole"> 确 定 </el-button>
        </span>
      </el-dialog>
      <!-- bb添加角色的对话框 -->
      <el-dialog
        title="添加角色"
        width="30%"
        :visible.sync="addtRoleDialog"
        @close="addRoleDialogClosed"
      >
        <el-form
          ref="addRoleRef"
          :model="addtRoleForm"
          :rules="addRoleFormRules"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="addtRoleForm.roleName"
              prop="roleDesc"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addtRoleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button @click="addtRoleDialog = false">取 消</el-button>
          <el-button type="primary" @click="addRole"> 确 定 </el-button>
        </span>
      </el-dialog>
      <!-- bb设置权限的对话框 -->
      <el-dialog
        title="修改角色权限"
        :visible.sync="setRightDialog"
        width="30%"
        @close="setRightDialogClosed"
      >
        <el-tree
          :data="rightsList"
          :props="treeProps"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="defKeys"
          ref="treeRef"
        ></el-tree>
        <span slot="footer">
          <el-button @click="setRightDialog = false">取 消</el-button>
          <el-button type="primary" @click="setRights()"> 确 定 </el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      editRoleDialog: false,
      addtRoleDialog: false,
      setRightDialog: false,
      rightsList: [],
      // 角色的三级权限ID
      defKeys: [],
      roleId: '',
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      editRoleForm: {
        id: '',
        roleName: '',
        roleDesc: ''
      },
      addtRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getRoLesList()
  },
  methods: {
    async getRoLesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    openEditRole (e) {
      this.editRoleDialog = true
      this.editRoleForm.id = e.id
      this.editRoleForm.roleName = e.roleName
      this.editRoleForm.roleDesc = e.roleDesc
    },
    async modifytRole () {
      const { data: res } = await this.$http.put('roles/' + this.editRoleForm.id, {
        roleName: this.editRoleForm.roleName,
        roleDesc: this.editRoleForm.roleDesc
      })
      if (res.meta.status !== 200) {
        this.$message.error('修改角色信息失败')
      }
      this.$message.success('修改角色信息成功')
      this.getRoLesList()
      this.editRoleDialog = false
      console.log(res)
    },
    async deletRole (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除角色失败')
      }
      this.$message.success('删除角色成功')
      this.getRoLesList()
    },
    openAddRole () {
      this.addtRoleDialog = true
    },
    async addRole () {
      const { data: res } = await this.$http.post('roles', this.addtRoleForm)
      console.log(res)
      if (res.meta.status !== 201) {
        this.$message.error('创建角色失败')
      }
      this.$message.success('创建角色成功')
      this.addtRoleDialog = false
      this.$refs.addRoleRel.resetFields()
      this.getRoLesList()
    },
    addRoleDialogClosed () {
      this.$refs.addRoleRef.resetFields()
    },
    async removeRightById (role, rightId) {
      const confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      role.children = res.data
    },
    async showSetRightDialog (role) {
      this.roleId = role.id
      this.setRightDialog = true
      const { data: res } = await this.$http.get('rights/tree')
      this.rightsList = res.data
      this.getLeafkeys(role, this.defKeys)
    },
    // 递归获取角色所有三级权限的id，以此显示角色所拥有的权限
    getLeafkeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafkeys(item, arr))
    },
    async setRights () {
      const allRightKeys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const allRifhtsEtr = allRightKeys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: allRifhtsEtr })
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRoLesList()
      this.setRightDialog = false
    },
    setRightDialogClosed () {
      this.defKeys = []
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 20px;
}
.bdTop {
  border-top: 1px solid #eee;
}
.bdBottom {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 7px;
}
.vCenter {
  display: flex;
  align-items: center;
}
</style>
